package com.wf.DouDiZhuOL.net.http;

import java.util.concurrent.Executors;

import com.wf.DouDiZhuOL.MainFrame;
import com.wf.DouDiZhuOL.util.Config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class HttpServer {
	private NioEventLoopGroup bossGroup = null;
	private NioEventLoopGroup workGroup = null;
	
	public void startServer() 
	{
		bossGroup = new NioEventLoopGroup(0, Executors.newCachedThreadPool());
		workGroup = new NioEventLoopGroup(0, Executors.newCachedThreadPool());
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workGroup);
		bootstrap.channel(NioServerSocketChannel.class);
		bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel ch) throws Exception 
			{
				ChannelPipeline pipeline = ch.pipeline();
				/*http request 解码*/
				pipeline.addLast(new HttpRequestDecoder());
				pipeline.addLast(new HttpObjectAggregator(65536));
				/*http response 编码*/
				pipeline.addLast(new HttpResponseEncoder());
				pipeline.addLast(new ChunkedWriteHandler());
				/*http response handler */
				pipeline.addLast(new HttpOutHandler());
				/*http request handler */
				pipeline.addLast(new HttpInHandler());
			}
		});
		int port = Config.getInstance().get(Config.SERVER_CONFIG_PATH, "localPort", 8586);
		MainFrame.setText("绑定端口：" + port);
		bootstrap.bind(port);
	}
}
